# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.


class ApplicationController < ActionController::Base
  
  model :FlickrImage
  
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_linklens_session_id'
  
  before_filter :init_session, :context_present, :cookie_setup
  
  def cookie_setup
    cookies[:_linklens_session_id] ||= { :value => 'true', :expires => 10.seconds.from_now }
  end
  
  def default_url_options(options)
    { :_linklens_session_id => session.session_id } unless cookies[:_linklens_session_id]
    #http://72.14.253.104/search?q=cache:CimcXwoTP5cJ:hellonline.com/blog/%3Fp%3D100+rails+mobile+session+cookies&hl=en&ct=clnk&cd=1&gl=us&client=safari
    #http://en.wikipedia.org/wiki/Getting_Things_Done
  end
  
  def context_present
    @context_elements = session_user.contexts
    @context_present = @context_elements.count > 0
    @recent_elements = session_user.recents
    return true
  end
  
  def init_session
    @session_user = session_user
  end
  
  def session_user
    return @session_user unless @session_user.nil?
      #ar_session = Session.find_by_session_id(session.session_id) 
      user = User.find(:first,
                       :select=> 'u.*',
                       :joins=>' u JOIN sessions_users su ON su.user_id = u.id', 
                       :conditions=>['su.session_id = ?',session.session_id])
    if user.nil?
     # begin
        user = User.new
        user.save!
        stmt = "INSERT INTO sessions_users (user_id, session_id) VALUES (#{user.id},'#{session.session_id}')"
        ActiveRecord::Base.connection.insert(stmt)
     # rescue
        
        # need this becasue when app first starts up
        # seems like session object gets created after this, so need
        # to catch error - originally used session.model[:id]
        
        # TODO can we create our own session id, place it in the sessions table and even in the session.model[:id] 
        # and then xhtml links will be rewritten appropriately and we'll have a session object on the first call
        
        # should pull out the latest 1.2. rails stuff from svn and search for where session gets initialized to be dropped into
        # outgoing headers - maybe we could turn off session support, and implement it ourselves???
        
     # end
    end
    return user
  end
end
